<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form
          :model="where"
          label-width="77px"
          class="ele-form-search"
          @keyup.enter.native="reload"
          @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="所属学校:">
              <el-select
                  filterable
                  clearable
                  v-model="where.organization"
                  @change="getSceneList"
                  size="small"
                  placeholder="-请选择所属学校-"
                  class="ele-block">
                <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="所属场地:">
              <el-select
                  filterable
                  clearable
                  v-model="where.scene_id"
                  @change="$forceUpdate()"
                  size="small"
                  placeholder="-请选择所属场地-"
                  class="ele-block">
                <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="班牌名称:">
              <el-input
                  clearable
                  v-model="where.name"
                  placeholder="请输入班牌名称"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button
                  type="primary"
                  icon="el-icon-search"
                  class="ele-btn-icon"
                  @click="reload">查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table
          ref="table"
          :where="where"
          :datasource="url"
          :columns="columns"
          :selection.sync="selection"
          height="calc(100vh - 315px)">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button
              size="small"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="openEdit(null)"
              v-if="permission.includes('sys:equip:add')">添加
          </el-button>
          <el-button
              size="small"
              type="danger"
              icon="el-icon-delete"
              class="ele-btn-icon"
              @click="removeBatch"
              v-if="permission.includes('sys:equip:dall')">删除
          </el-button>
          <el-button
              size="small"
              type="primary"
              class="ele-btn-icon"
              @click="batchSetting()">批量设置
          </el-button>
          <el-button
              size="small"
              type="primary"
              class="ele-btn-icon"
              @click="showBatchSetPic = true">批量设置轮播图
          </el-button>
        </template>
        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-link
              type="primary"
              :underline="false"
              @click="remoteOpen(row)"
              v-if="permission.includes('sys:equip:edit')">远程开门
          </el-link>
          <el-link
              type="primary"
              :underline="false"
              @click="openRecord(row)"
              v-if="permission.includes('sys:equip:edit')">开门记录
          </el-link>
          <el-link
              type="primary"
              :underline="false"
              icon="el-icon-edit"
              @click="openEdit(row)"
              v-if="permission.includes('sys:equip:edit')">修改
          </el-link>
          <el-link
              type="primary"
              :underline="false"
              icon="el-icon-s-custom"
              @click="openManage(row)">管理员
          </el-link>
          <el-popconfirm
              class="ele-action"
              title="确定要删除此电子班牌吗？"
              @confirm="remove(row)">
            <el-link
                type="danger"
                slot="reference"
                :underline="false"
                icon="el-icon-delete"
                v-if="permission.includes('sys:equip:delete')">删除
            </el-link>
          </el-popconfirm>
        </template>
        <!-- 在线状态列 -->
        <template slot="online" slot-scope="{row}">
          <el-tag v-if="row.online == 0" type="danger" size="small">离线</el-tag>
          <el-tag v-if="row.online >0" type="success" size="small">在线</el-tag>
        </template>

      </ele-pro-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <equip-edit
        v-if="showEdit"
        :data="current"
        :visible.sync="showEdit"
        @done="reload"/>
    <!-- 批量设置弹窗 -->
    <equip-batch
        :data="current"
        :visible.sync="showBatch"
        @done="reload"/>
    <!-- 批量设置弹窗 -->
    <equip-record
        :data="current"
        :visible.sync="showRecord"
        @done="reload"/>
    <equip-manage
        v-if="showManage"
        :data="manageCurrent"
        :visible.sync="showManage"/>
    <batch-set-pic v-if="showBatchSetPic" :visible.sync="showBatchSetPic" @done="reload" />
    <el-dialog
        title="提示"
        :visible.sync="remoteOpenData.visible"
        width="260px">
      <div style="height: 60px;display: flex; justify-items: center; align-items: center; justify-content: center;">
        <template v-if="remoteOpenData.equip.online">
          <div v-if="remoteOpenData.status === 'wait' || remoteOpenData.status === 'loading'"
               v-loading="remoteOpenData.status === 'loading'" element-loading-text="下发开门指令中...">
            确定要远程打开设备[{{ remoteOpenData.equip.code }}]吗?
          </div>
          <div v-else style="text-align: center;">
            <i v-if="remoteOpenData.status === 'success'" class="el-icon-success" style="color: #67C23A; font-size: 48px"></i>
            <i v-if="remoteOpenData.status === 'error'" class="el-icon-error" style="color: #F56C6C; font-size: 48px"></i>
            <div>{{ remoteOpenData.msg }}</div>
          </div>
        </template>
        <div v-else style="text-align: center;">
          <i class="el-icon-warning" style="color: #E6A23C; font-size: 48px"></i>
          <div>当前设备[{{ remoteOpenData.equip.code }}]不在线,无法开门!</div>
        </div>
      </div>
      <div v-if="remoteOpenData.status !== 'loading'" slot="footer" class="dialog-footer">
        <el-button v-if="remoteOpenData.status === 'wait'" @click="remoteOpenData.visible = false">取 消</el-button>
        <el-button v-if="remoteOpenData.equip.online" type="primary" @click="remoteOpenSend">
          {{remoteOpenData.status === 'error' ? '重 试' : '确 定'}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import EquipEdit from './equip-edit';
import EquipBatch from './equip-batch';
import EquipRecord from './equip-record';
import EquipManage from './equip-manage';
import BatchSetPic from './batch-set-pic.vue';

export default {
  name: 'ExamEquip',
  components: {EquipEdit, EquipBatch, EquipRecord, EquipManage, BatchSetPic},
  computed: {
    ...mapGetters(["permission"]),
  },
  data() {
    return {
      // 表格数据接口
      url: '/equip/index',
      // 表格列配置
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          prop: 'id',
          label: 'ID',
          width: 60,
          align: 'center',
          showOverflowTooltip: true,
          fixed: "left"
        },
        {
          prop: 'organization_name',
          label: '所属学校',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'grade_name',
          label: '所属年级',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'clazz_name',
          label: '所属班级',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'scene_id_name',
          label: '所属场地',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'name',
          label: '班牌名称',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'online',
          label: '在线状态',
          align: 'center',
          width: 100,
          slot: 'online',
        },
        {
          prop: 'code',
          label: '设备编码',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'account',
          label: '账号',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'password',
          label: '密码',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'sort',
          label: '显示顺序',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'note',
          label: '备注',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'create_time',
          label: '创建时间',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
          formatter: (row, column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },
        {
          prop: 'device_update',
          label: '更新时间',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
          formatter: (row, column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 150,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: "right"
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      manageCurrent: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 是否显示批量设置弹窗
      showBatch: false,
      // 是否显示开门记录弹窗
      showRecord: false,
      showManage: false,
      showBatchSetPic: false,
      showRemoteOpen: false,
      // 学院列表
      schoolList: [],
      // 场地列表
      sceneList: [],
      remoteOpenData: {
        visible: false,
        equip: {},
        status: 'wait',
      }
    };
  },
  mounted() {
    // 获取学院列表
    this.getSchoolList();
  },
  methods: {
    /* 刷新表格 */
    reload() {
      this.$refs.table.reload({where: this.where});
    },
    /* 重置搜索 */
    reset() {
      this.where = {};
      this.reload();
    },
    /* 显示编辑 */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    /* 显示开门记录 */
    openRecord(row) {
      this.current = row;
      this.showRecord = true;
    },
    remoteOpen(row) {
      this.remoteOpenData.equip = row
      this.remoteOpenData.status = 'wait'
      this.remoteOpenData.visible = true
    },
    remoteOpenSend() {
      if (this.remoteOpenData.status === 'success') {
        this.remoteOpenData.visible = false
        return
      }
      this.remoteOpenData.status = 'loading'
      this.$http.post('/equip/remoteOpen', {id: this.remoteOpenData.equip.id}).then(res => {
        if (res.data.code === 0) {
          let times = 0
          const interval = setInterval(async () => {
            const remoteOpenStatus = await this.$http.post('/equip/remoteOpenStatus', {id: this.remoteOpenData.equip.id})
            if (remoteOpenStatus.data.data.status === 0) {
              clearInterval(interval)
              this.remoteOpenData.status = 'success'
              this.remoteOpenData.msg = '开门成功'
            } else {
              times++
              if (times >= 30) {
                clearInterval(interval)
                this.remoteOpenData.status = 'error'
                this.remoteOpenData.msg = '下发指令超时,请检查设备状态!'
              }
            }
          }, 1000)
        } else {
          this.remoteOpenData.status = 'error'
          this.remoteOpenData.msg = res.data.msg
        }
      }).catch(e => {
        this.remoteOpenData.status = 'error'
        this.remoteOpenData.msg = e.message
      })
    },
    openManage(row) {
      this.manageCurrent = row;
      this.showManage = true;
    },
    /* 删除 */
    remove(row) {
      const loading = this.$loading({lock: true});
      this.$http.post('/equip/delete', {id: row.id}).then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    /* 批量删除 */
    removeBatch() {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      this.$confirm('确定要删除选中的电子班牌吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({lock: true});
        this.$http.post('/equip/delete', {id: this.selection.map(d => d.id)}).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      }).catch(() => {
      });
    },
    // 批量设置
    batchSetting() {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      this.current = {batch: this.selection.map(d => d.id)};
      this.showBatch = true;
    },
    /**
     * 获取组织列表
     */
    getSchoolList() {
      if (this.where.organization) {
        this.where.scene_id = null;
        this.$forceUpdate();
        this.getSceneList();
      }
      this.$http.get('/school/getSchoolList').then(res => {
        if (res.data.code === 0) {
          this.schoolList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },

    /**
     * 获取楼栋列表
     */
    getSceneList() {
      if (this.where.scene_id) {
        this.where.scene_id = null;
        this.$forceUpdate();
      }
      this.$http.post('/sitescene/getSceneList', {oid: this.where.organization}).then(res => {
        if (res.data.code === 0) {
          this.sceneList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
  }
}
</script>

<style scoped>
</style>
